package com.cszy.yydqbfq.ui.fragment

import HomeFragmentPagerAdapter
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.cszy.yydqbfq.R
import com.cszy.yydqbfq.databinding.FragmentIndexBinding

import com.cszy.yydqbfq.adapter.IndexListAdapter
import com.cszy.yydqbfq.adapter.indexGridAdapter
import com.cszy.yydqbfq.base.BaseVMFragment
import com.cszy.yydqbfq.bean.AudioItemBean
import com.cszy.yydqbfq.bean.Song
import com.cszy.yydqbfq.common.AppConstants
import com.cszy.yydqbfq.common.PlaylistRepository

import com.cszy.yydqbfq.dialog.BottomPopupWithGeDanRecycler
import com.cszy.yydqbfq.dialog.FcmFirstDialog
import com.cszy.yydqbfq.dialog.FcmShowDialog
import com.cszy.yydqbfq.dialog.FunctionGuideDialog
import com.cszy.yydqbfq.dialog.PermissoTipDialog
import com.cszy.yydqbfq.dialog.UserAgreementDialog
import com.cszy.yydqbfq.dialog.UserRefusedPermissonDialog
import com.cszy.yydqbfq.ext.launch
import com.cszy.yydqbfq.ext.toast

import com.cszy.yydqbfq.ui.activity.MusicListActivity
import com.cszy.yydqbfq.ui.activity.PlayDetailActivity
import com.cszy.yydqbfq.utils.SpUtils
import com.cszy.yydqbfq.utils.TimeUtils
import com.cszy.yydqbfq.viewmodel.IndexViewModel
import com.cszy.yydqbfq.viewmodel.MainViewModel
import com.google.android.material.tabs.TabLayoutMediator
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.XXPermissions
import com.hlyj.http.ad.NewGroMoreFeedAdManager
import com.hlyj.http.base.tool.lib_hlyj_base.Constants
import com.hlyj.http.base.tool.lib_hlyj_base.bean.music.MusicListBean
import com.hlyj.http.base.tool.lib_hlyj_base.utils.BaseAppConstans
import com.hlyj.http.base.tool.lib_hlyj_base.utils.BaseModuleSpUtils

import com.hnyyac.ad.mds.IAdView
import com.hnyyac.ad.mds.IAdViewListener
import com.hnyyac.ad.mds.manager.AdManager
import com.hnyyac.ad.mds.manager.AdManager.AdLoadListener
import com.hnyyac.ad.mds.utils.BaseAdConstants
import kotlinx.coroutines.Runnable
import kotlinx.coroutines.launch
import org.litepal.LitePal


class IndexFragment : BaseVMFragment<IndexViewModel, FragmentIndexBinding>(), IAdViewListener {

    private var fcmDialog: FcmFirstDialog? = null
    private var fcmshowDialog: FcmShowDialog? = null
    private var hasShownInterstitialAd = false
    private val adShownItems = mutableSetOf<Int>()

    // 正确的声明方式
    private val viewpagerAdapter by lazy {
        HomeFragmentPagerAdapter(requireActivity(), mViewModel.getIndexGridData())
    }

    var type_proces: String? = null //功能入口类型
    var app_process: String? = "0" //整个应用流程
    override fun initView(savedInstanceState: Bundle?) {
        mViewModel.init(requireActivity())
        app_process = SpUtils.getInstance().getString(BaseAppConstans.APP_PROCESS)
        initTabWithViewPager()
    }

    private fun initTabWithViewPager() {
        mBinding.viewPager.adapter = viewpagerAdapter
        mBinding.viewPager.offscreenPageLimit = 1 // 预加载页面数量
        mBinding.tabLayout.setSelectedTabIndicatorHeight(0)
        mBinding.tabLayout.tabRippleColor = null
        // 连接 TabLayout 和 ViewPager2
        TabLayoutMediator(mBinding.tabLayout, mBinding.viewPager) { tab, position ->
            tab.text = mViewModel?.getIndexGridData()?.getOrNull(position)?.title ?: ""
            tab.setCustomView(R.layout.custom_tab_layout)
        }.attach()


        // 添加 Tab 点击监听器
        mBinding.tabLayout.addOnTabSelectedListener(object : com.google.android.material.tabs.TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: com.google.android.material.tabs.TabLayout.Tab?) {
                // 获取选中 tab 的位置
                val position = tab?.position?.takeIf { it > 0 } ?: return

                // 获取 ViewPager 中对应的 fragment 实例
                val fragment = viewpagerAdapter.getCategoryFragment(position) ?: return

                // 检查该位置是否第一次点击
                if (!adShownItems.contains(position)) {
                    // 第一次点击，展示插屏广告
                    fragment.showFirstAd()
                    adShownItems.add(position)
                }
            }

            override fun onTabUnselected(tab: com.google.android.material.tabs.TabLayout.Tab?) {}
            override fun onTabReselected(tab: com.google.android.material.tabs.TabLayout.Tab?) {}
        })
    }


    override fun initData() {
        when (app_process) {
            "0" -> showFCM()
            "1" -> app_process_1()
            "2" -> app_process_2()
        }
    }

    override fun initListener() {
        //本地音乐获取
        mBinding.ivIntoLocal.setOnClickListener {
            showMediaPermissionDialog()
        }
    }



    override fun onResume() {
        super.onResume()
        if (app_process == "0") {
            //第一次显示防沉迷diaolog
            if (!SpUtils.getInstance().getBoolean(AppConstants.IS_SHOW_FCM_DIALOG)) {
                showDialog_fcmDialog()
            } else {
                if (fcmDialog != null) {
                    fcmDialog?.dismiss()
                }
                if (fcmshowDialog != null) {
                    fcmshowDialog?.dismiss()
                }
            }

        }
        val localList = LitePal.findAll(AudioItemBean::class.java)
        if (localList.isNotEmpty()) {
            // 更新 UI（）
            mBinding.ivIntoLocal.visibility = View.GONE
        }else{
            mBinding.ivIntoLocal.visibility = View.VISIBLE
        }
    }

    fun app_process_1() {
        type_proces = "第一次进首页插屏"
        AdManager.loadChapin_nocache(
            requireActivity(),
            2,
            this,
            object : AdLoadListener {
                override fun onAdLoadFailed(ad: IAdView?) {
                    Log.e("qin", "首页流程1插屏加载失败")
                    if (!SpUtils.getInstance()
                            .getBooleanWithTimeoutCheck(BaseAppConstans.IS_SHOW_FUNCTION_DIALOG)
                    ) {
                        if (!isAdded) return
                        showFunctionGuideDialog(requireActivity())
                    }
                }
            })
    }

    fun app_process_2() {
        type_proces = "第一次进首页插屏"
        AdManager.loadChapin_nocache(
            requireActivity(),
            2,
            this,
            object : AdLoadListener {
                override fun onAdLoadFailed(ad: IAdView?) {
                    Log.i("qin", "首页流程2插屏加载失败")
                    if (!SpUtils.getInstance()
                            .getBooleanWithTimeoutCheck(BaseAppConstans.IS_SHOW_FUNCTION_DIALOG)
                    ) {
                        showFunctionGuideDialog(requireActivity())
                    }

                }
            })
    }

    /**
     * 显示功能引导弹窗
     */
    private fun showFunctionGuideDialog(context: Context) {
        // 创建对话框实例
        val dialog = FunctionGuideDialog(context)
        dialog.setCancelable(false) // 设置对话框不可取消
        dialog.setOnGuideDialogListener(object : FunctionGuideDialog.onGuideDialogListener {
            override fun btnOnclick() {
                 closeGuide()
            }

            private fun closeGuide() {
                dialog.dismiss() // 关闭对话框
                // 处理点击引导内容的回调
                type_proces = "功能弹窗"
                AdManager.loadVideo_nocache(
                    requireActivity(),
                    4,
                    this@IndexFragment,
                    object : AdLoadListener {
                        override fun onAdLoadFailed(ad: IAdView?) {
                             if (app_process == "0"){
                                 showAgreementtDialog()
                             }
                        }
                    })
            }

            override fun btnOnclose() {
                closeGuide()
            }
        })

        // 显示对话框
        dialog.show()
    }

    override fun loadAudioList() {
        showLoading("正在获取本地音乐")
        lifecycleScope.launch { // 使用 lifecycleScope 确保协程与 Activity 生命周期绑定
            try {
                // 调用 suspend 函数获取数据
                val audioList = mViewModel.getAudioInfoListSync()
                dismissLoading()
                // 更新 UI（）
                mBinding.ivIntoLocal.visibility = View.GONE
                toast("已成功导入本地歌曲至歌单")

            } catch (e: Exception) {
                // 处理错误（例如 Toast 提示）
                dismissLoading()
                toast("加载音频列表失败: ${e.message}")
            }
        }
    }


    fun showDialog_fcmDialog() {
        SpUtils.getInstance().putBoolean(AppConstants.IS_SHOW_FCM_DIALOG, true)
        fcmDialog = FcmFirstDialog(requireActivity())
        fcmDialog?.setCancelable(false)
        fcmDialog?.show()
    }

    fun showDialog_fcmDialog_open() {
        fcmshowDialog = FcmShowDialog(requireActivity())
        fcmshowDialog?.setCancelable(false)
        fcmshowDialog?.show()
    }

    private fun showFCM() {
        //是否开启显示防沉迷dialog
        if (SpUtils.getInstance().getBoolean(AppConstants.ISOPEN_FCM)) {
            if (TimeUtils.isNightTime()) {
                showDialog_fcmDialog_open()
            }
        }
    }

    /**
     * 显示隐私协议弹窗
     */
    private fun showAgreementtDialog() {
        if (SpUtils.getInstance().getBoolean(BaseAppConstans.isAgreeMent)) {

            return
        }
        var dialog = UserAgreementDialog(requireActivity())
        dialog!!.show()
        dialog!!.setPrivateId(
            "您好" + "(" + BaseModuleSpUtils.getInstance().getString(Constants.PRIVACYID) + ")"
        )
        dialog!!.setCancelable(false)
        dialog!!.setOnAgreementListener(object : UserAgreementDialog.AgreementDialogListner {
            override fun onDialogListener(clickType: Boolean) {
                if (clickType) {
                    SpUtils.getInstance().putBoolean(BaseAppConstans.isAgreeMent, true)
                    if (!SpUtils.getInstance().getBoolean(BaseAppConstans.IS_SHOW_YINSI_CHAPIN)) {
                        type_proces = "特殊情况点击同意隐私的插屏"
                        AdManager.loadChapin_nocache(
                            requireActivity(),
                            10,
                            this@IndexFragment,
                            object : AdLoadListener {
                                override fun onAdLoadFailed(ad: IAdView?) {


                                }
                            })
                    }

                } else { //拒绝隐私协议
                    activity?.finish()

                }
            }
        })
    }

    override fun onTrigger(adView: IAdView) {

    }

    override fun onAdShow(adView: IAdView) {
        when (type_proces) {
            "功能返回插屏" -> {
                SpUtils.getInstance()
                    .putBoolean(BaseAppConstans.IS_SHOW_YINSI_CHAPIN, true)//已经弹过了功能返回的插屏
            }

            "功能弹窗" -> {
                SpUtils.getInstance().putBoolean(BaseAppConstans.IS_SHOW_FUNCTION_DIALOG, true)
            }
        }
    }

    override fun onAdClick(adView: IAdView) {

    }

    override fun onAdClose(adView: IAdView) {
        // 检查 Fragment 是否仍然有效
        if (!isAdded || isDetached || activity == null) {
            return // 如果 Fragment 无效，直接返回
        }
        when (type_proces) {
            "第一次进首页插屏" -> {
                if (!SpUtils.getInstance()
                        .getBooleanWithTimeoutCheck(BaseAppConstans.IS_SHOW_FUNCTION_DIALOG)
                ) {
                    showFunctionGuideDialog(requireActivity())
                } else {
                    if (!SpUtils.getInstance().getBoolean(BaseAppConstans.isAgreeMent)) {
                        showAgreementtDialog()
                    }
                }
            }


            "功能弹窗关闭广告" -> {
                if (app_process == "1") {
                    showAgreementtDialog()
                }

            }

            "功能弹窗" -> {
                if (app_process == "1") {
                    type_proces = "功能弹窗关闭广告"
                    showInterstitialWithAgree()
                }
            }

            "点击本地音乐" -> {
                var bundle = Bundle()
                bundle.putString("category", "本地音乐")
                launch(bundle, MusicListActivity::class.java)
            }
        }
    }

    private fun showInterstitialWithAgree() {
        AdManager.loadChapin_nocache(requireActivity(), 9, this, object : AdLoadListener {
            override fun onAdLoadFailed(ad: IAdView?) {
                showAgreementtDialog()
            }
        })
    }

    override fun onError(msg: String) {

    }

    override fun onLoadError(adView: IAdView) {

    }

    override fun onSuccess(adView: IAdView) {

    }

    override fun onLoad(adView: IAdView) {

    }

    override fun onSkipped() {

    }

    override fun onNoAd() {

    }

    override fun onTimeOut() {

    }

    override fun onDestroyView() {
        super.onDestroyView()
    }
}